package com.yuexin.project.finance.bill.controller;

import com.alibaba.fastjson.JSON;
import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.framework.aspectj.lang.annotation.Log;
import com.yuexin.framework.aspectj.lang.enums.BusinessType;
import com.yuexin.framework.web.controller.BaseController;
import com.yuexin.framework.web.domain.AjaxResult;
import com.yuexin.framework.web.page.TableDataInfo;
import com.yuexin.project.finance.bill.domain.Bill;
import com.yuexin.project.finance.bill.formbean.BillListFormBean;
import com.yuexin.project.finance.bill.service.IBillService;
import com.yuexin.project.system.group.domain.GroupUser;
import com.yuexin.project.system.group.formbean.GroupsListFormBean;
import com.yuexin.project.system.group.service.IGroupUserService;
import com.yuexin.project.system.group.service.IGroupsService;
import com.yuexin.project.system.user.domain.User;
import com.yuexin.project.system.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 用户账单 信息操作处理
 *
 * @author zoncont.ahanu
 * @date 2019-03-08
 */
@Controller
@RequestMapping("/finance/bill")
@Api(value = "用户账单 信息操作处理", description = "用户账单 信息操作处理")
public class BillController extends BaseController {
    private String prefix = "finance/bill";

    @Autowired
    private IBillService billService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGroupsService groupsService;
    @Autowired
    private IGroupUserService groupUserService;

    @RequiresPermissions("finance:bill:view")
    @GetMapping()
    @ApiOperation("用户账单页面")
    public String bill(ModelMap mmap) {
        mmap.put("users", userService.selectByCompanyId(ShiroUtils.getCompanyId()));
        return prefix + "/bill";
    }

    @RequiresPermissions("finance:bill:list")
    @PostMapping("/list")
    @ResponseBody
    @ApiOperation("查询用户账单列表")
    public TableDataInfo selectBillLists(BillListFormBean form) {
        form.setCompanyId(ShiroUtils.getCompanyId());
        form.setFilterBillType("3");
        startPage();
        return getDataTable(billService.selectBillLists(form));
    }

    /**
     * 根据用户新增用户账单
     */
    @GetMapping("/add")
    @ApiOperation("新增用户账单")
    public String add(ModelMap mmap) {
        mmap.put("users", userService.selectByCompanyId(ShiroUtils.getCompanyId()));
        mmap.put("userJson", JSON.toJSONString(userService.selectByCompanyId(ShiroUtils.getCompanyId())));
        return prefix + "/add";
    }


    /**
     * 新增保存用户账单
     */
    @RequiresPermissions("finance:bill:add")
    @Log(title = "用户账单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @ApiOperation("新增保存用户账单")
    @Transactional
    public AjaxResult addSave(Bill bill) {
        return add(bill);
    }

    /**
     * 根据用户组新增用户账单
     */
    @GetMapping("/batchadd")
    @ApiOperation("新增用户账单")
    public String batchAdd(ModelMap mmap) {
        GroupsListFormBean group = new GroupsListFormBean();
        group.setCompanyId(ShiroUtils.getCompanyId());
        mmap.put("groups", groupsService.selectGroupsList(group));
        return prefix + "/batchadd";
    }

    /**
     * 新增保存用户账单
     */
    @RequiresPermissions("finance:bill:batchadd")
    @Log(title = "用户账单", businessType = BusinessType.INSERT)
    @PostMapping("/batchadd")
    @ResponseBody
    @ApiOperation("新增保存用户账单")
    @Transactional
    public AjaxResult batchAddSave(Bill bill) {
        GroupUser groupUser = new GroupUser();
        groupUser.setGroupId(bill.getGroupId());
        List<GroupUser> groupUserList = groupUserService.selectGroupUserList(groupUser);
        groupUserList.stream().forEach(item -> {
            bill.setUserId(Long.valueOf(item.getUserId()));
            add(bill);
        });
        return AjaxResult.success();
    }

    private AjaxResult add(Bill bill){
        User user = userService.selectUserById(bill.getUserId());
        BigDecimal money = user.getMoney() == null ? new BigDecimal(0) : user.getMoney();
        money = money.add(bill.getPrice());
        user.setMoney(money);
        userService.updateUserInfo(user);
        bill.setUserName(user.getLoginName());
        bill.setMoney(money);
        bill.setCreateBy(ShiroUtils.getUser().getLoginName());
        bill.setCompanyId(ShiroUtils.getCompanyId());
        bill.setCreateTime(new Date());
        return toAjax(billService.insertBill(bill));
    }

    @GetMapping("/edit/{billId}")
    @ApiOperation("冲账")
    public String edit(@PathVariable("billId") Integer billId, ModelMap mmap) {
        Bill bill = billService.selectBillById(billId);
        mmap.put("bill", bill);
        return prefix + "/edit";
    }

    @RequiresPermissions("finance:bill:edit")
    @Log(title = "冲账", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @ApiOperation("冲账")
    public AjaxResult editSave(Bill form) {
        Bill bill = billService.selectBillById(form.getBillId());
        Date time = new Date();
        User user = userService.selectUserByLoginName(bill.getUserName());
        BigDecimal money = user.getMoney() == null ? new BigDecimal(0) : user.getMoney();
        money = money.subtract(bill.getPrice());
        user.setMoney(money);
        userService.updateUserInfo(user);

        Bill rushBill = new Bill();
        rushBill.setBillType("2");
        rushBill.setDescribes(bill.getSerialNo());
        rushBill.setCreateTime(time);
        rushBill.setCreateBy(ShiroUtils.getUser().getLoginName());
        rushBill.setCompanyId(ShiroUtils.getCompanyId());
        rushBill.setPrice(bill.getPrice());
        rushBill.setMoney(money);
        rushBill.setPrice(bill.getPrice());
        rushBill.setUserName(user.getLoginName());
        rushBill.setRemark(form.getRemark());
        billService.insertBill(rushBill);

//        bill.setMoney(money);
        bill.setPrice(null);
        bill.setDescribes(rushBill.getSerialNo());
        bill.setUpdateBy(ShiroUtils.getUser().getLoginName());
        bill.setUpdateTime(time);
        return toAjax(billService.updateBill(bill));
    }

    /**
     * 删除用户账单
     */
    @RequiresPermissions("finance:bill:remove")
    @Log(title = "用户账单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    @ApiOperation("删除用户账单")
    public AjaxResult remove(String ids) {
        return toAjax(billService.deleteBillByIds(ids));
    }

}
